package com.gitee.qdbp.filling.support;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.gitee.qdbp.filling.api.EntityDataTypedFillService;
import com.gitee.qdbp.filling.api.EntityFillType;
import com.gitee.qdbp.filling.biz.BaseEntityDataFillService;

/**
 * 实体数据处理类的Spring实现类
 *
 * @author zhaohuihua
 * @version 20210113
 */
public class SpringEntityDataFillService extends BaseEntityDataFillService
        implements InitializingBean, ApplicationContextAware {

    @Override
    protected EntityDataTypedFillService findService(String type) {
        return this.services.get(type);
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, EntityDataTypedFillService> maps = context.getBeansOfType(EntityDataTypedFillService.class);
        for (EntityDataTypedFillService bean : maps.values()) {
            EntityFillType annotation = bean.getClass().getAnnotation(EntityFillType.class);
            if (annotation != null && annotation.value().length > 0) {
                for (String type : annotation.value()) {
                    this.services.put(type, bean);
                }
            }
        }
    }

    private ApplicationContext context;
    private final Map<String, EntityDataTypedFillService> services = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }

}
